<template>
  <div>
    <!-- 角色列表页面顶部 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="addRolesdialogVisible=true">添加角色</el-button>
      <!-- 角色列表表格 -->
      <el-table border stripe :data="rolesList">
        <el-table-column type="expand" label="展开列">
          <template v-slot="scope">
            <!-- <pre>{{scope.row}}</pre> -->
            <el-row
              :class="['bdbottom',i1===0?'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="delRightById(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-arrow-right"></i>
              </el-col>
              <!-- 渲染二级，三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2===0?'':'bdtop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="7">
                    <el-tag
                      type="warning"
                      closable
                      @close="delRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-arrow-right"></i>
                  </el-col>
                  <el-col :span="17">
                    <el-tag
                      closable
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      @close="delRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="level" label="操作" width="300px">
          <template slot-scope="scope">
            <!-- <pre>{{scope.row}}</pre> -->
            <el-row>
              <el-button type="primary" size="mini" @click="editRoles(scope.row.id)">编辑</el-button>
              <el-button type="danger" size="mini" @click="delRoles(scope.row.id)">删除</el-button>
              <el-button type="warning" size="mini" @click="setRightDialog(scope.row)">分配权限</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹框Dialog -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesdialogVisible"
      width="70%"
      @close="addrolesDialogClosed"
    >
      <span slot="footer" class="dialog-footer">
        <el-form
          :model="addroles"
          :rules="addRolesRules"
          ref="addRolesRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addroles.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addroles.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="addRolesdialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="addRolesBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色弹框Dialog -->
    <el-dialog
      title="编辑角色"
      width="70%"
      @close="editrolesDialogClosed"
      :visible.sync="editRolesdialogVisible"
    >
      <span slot="footer" class="dialog-footer">
        <el-form
          :model="editroles"
          :rules="editRolesRules"
          ref="editRolesRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editroles.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editroles.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="editRolesdialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="editRolesBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <!-- <el-button type="text" @click="setRightDialogVisible">分配权限</el-button> -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 show-checkbox复选框 node-key="id"绑定唯一id值 default-expand-all默认打开所有节点 default-checked-keyss默认勾选已选中节点-->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data: function() {
    return {
      rolesList: [],
      addRolesdialogVisible: false,
      editRolesdialogVisible: false,
      addroles: {
        roleName: '',
        roleDesc: ''
      },
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 5,
            max: 100,
            message: '长度在 5 到 100 个字符',
            trigger: 'blur'
          }
        ]
      },
      editroles: {},
      editRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 5,
            max: 100,
            message: '长度在 5 到 100 个字符',
            trigger: 'blur'
          }
        ]
      },
      setRightDialogVisible: false,
      // 权限列表的所有数据
      rightsList: [],
      // 树形控件后面的label
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中节点的id数组
      defkeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取用户角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户角色列表失败')
      }
      this.rolesList = res.data
      console.log(res)
    },
    // 添加角色
    async addRolesBtn() {
      this.$refs.addRolesRef.validate(valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('添加失败')
        }
      })
      const { data: res } = await this.$http.post('roles', this.addroles)
      if (res.meta.status !== 201) {
        return this.$message.error('创建失败')
      }
      this.$message.success('添加成功')
      this.getRolesList()
      this.addRolesdialogVisible = false
      // console.log(res)
    },
    // ×掉重置(添加)
    addrolesDialogClosed() {
      this.$refs.addRolesRef.resetFields()
    },
    // 编辑角色
    async editRoles(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取当前角色失败失败')
      }
      this.editroles = res.data
      this.editRolesdialogVisible = true
      // console.log(res)
    },
    // ×掉重置(编辑)
    editrolesDialogClosed() {
      this.$refs.editRolesRef.resetFields()
    },
    // 编辑完成之后提交要先表单验证
    editRolesBtn() {
      this.$refs.editRolesRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('修改失败')
        }
        const { data: res } = await this.$http.put(
          'roles/' + this.editroles.roleId,
          this.editroles
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改错误')
        }
        this.getRolesList()
        this.editRolesdialogVisible = false
        // console.log(res)
      })
    },
    // 删除操作
    async delRoles(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        return err
      })
      // 如果用户确认了删除，则返回值为字符串confirm
      // 如果用户取消了删除，则返回字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('不要慌，还没有删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败，可能是权限不够')
      }
      this.$message.success('删除用户成功')
      this.getRolesList()
    },
    // 删除角色指定权限
    async delRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '请问现在是否要删除该权限',
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除了')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色权限失败')
      }
      // this.getRolesList()  会重新加载所有权限，这个只需要对现有角色进行更新即可
      role.children = res.data
      // console.log(res)
    },
    // 分配权限
    async setRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsList = res.data
      // 调用getLeafKeys进行递归，将三级权限添加到数组
      this.getLeafKeys(role, this.defkeys)
      console.log(res)
      console.log(this.defkeys)

      this.setRightDialogVisible = true
    },
    // 获取当前角色的所有三级权限id并天极爱到defkeys
    getLeafKeys(node, arr) {
      // 没有children属性了就可以判定是三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 重置
    setRightDialogClosed() {
      this.defkeys = []
    },
    // 分配权限
    async allotRights() {
      // 获取所有选中及半选的内容
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ]
      // 将数组转换成逗号拼接的字符串
      const idStr = keys.join(',')
      // 发送请求完成更新
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      console.log(res)
      this.setRightDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
// .el-dialog {
//   display: flex;
// }
// .el-form-item {
//   flex: 1;
// }
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
